<template>
  <div class="workflow-designer-page">
    <!-- 顶部标题栏 -->
    <div class="designer-header">
      <div class="header-left">
        <Button type="link" @click="handleBack">
          <template #icon><ArrowLeftOutlined /></template>
          返回
        </Button>
        <Divider type="vertical" />
        <span class="model-name">{{ modelInfo?.name || '流程设计器' }}</span>
      </div>
      <div class="header-right">
        <Space>
          <Button @click="handleSave">
            <template #icon><SaveOutlined /></template>
            保存
          </Button>
          <Button type="primary" @click="handleSaveAndDeploy">
            <template #icon><CloudUploadOutlined /></template>
            保存并部署
          </Button>
        </Space>
      </div>
    </div>

    <!-- BPMN 设计器 -->
    <div class="designer-content">
      <BpmnDesigner
        v-if="bpmnXml"
        v-model:bpmn-xml="bpmnXml"
        :show-properties="true"
        @save="handleDesignerSave"
      />
      <div v-else class="loading-container">
        <Spin size="large" tip="加载中..." />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { Button, Divider, Space, Spin, message } from 'ant-design-vue';
import {
  ArrowLeftOutlined,
  CloudUploadOutlined,
  SaveOutlined,
} from '@ant-design/icons-vue';

import type { ProcessModel } from '#/api/workflow';
import {
  deployProcessModelApi,
  getProcessModelBpmnApi,
  getProcessModelDetailApi,
  saveProcessModelBpmnApi,
} from '#/api/workflow';

import BpmnDesigner from '../components/bpmn-designer/index.vue';

const route = useRoute();
const router = useRouter();

const modelId = ref<string>('');
const modelInfo = ref<ProcessModel>();
const bpmnXml = ref<string>('');

// 加载模型信息
async function loadModelInfo() {
  try {
    const data = await getProcessModelDetailApi(modelId.value);
    modelInfo.value = data;
  } catch (error: any) {
    message.error(error?.msg || '加载模型信息失败');
  }
}

// 加载 BPMN XML
async function loadBpmnXml() {
  try {
    const data = await getProcessModelBpmnApi(modelId.value);
    bpmnXml.value = data.bpmnXml;
  } catch (error: any) {
    message.error(error?.msg || '加载流程图失败');
    // 如果加载失败，使用默认的空流程图
    bpmnXml.value = getDefaultBpmnXml();
  }
}

// 获取默认的 BPMN XML
function getDefaultBpmnXml(): string {
  const processId = modelInfo.value?.key || 'Process_1';
  const processName = modelInfo.value?.name || '新流程';
  
  return `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
                  xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
                  xmlns:dc="http://www.omg.org/spec/DD/20100524/DC"
                  xmlns:di="http://www.omg.org/spec/DD/20100524/DI"
                  id="Definitions_1"
                  targetNamespace="http://bpmn.io/schema/bpmn">
  <bpmn:process id="${processId}" name="${processName}" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="开始"/>
  </bpmn:process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_1">
    <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="${processId}">
      <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1">
        <dc:Bounds x="179" y="159" width="36" height="36"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds x="186" y="202" width="22" height="14"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</bpmn:definitions>`;
}

// 设计器保存回调
function handleDesignerSave(xml: string) {
  bpmnXml.value = xml;
}

// 保存
async function handleSave() {
  try {
    await saveProcessModelBpmnApi(modelId.value, bpmnXml.value);
    message.success('保存成功');
  } catch (error: any) {
    message.error(error?.msg || '保存失败');
  }
}

// 保存并部署
async function handleSaveAndDeploy() {
  try {
    // 先保存
    await saveProcessModelBpmnApi(modelId.value, bpmnXml.value);
    // 再部署
    await deployProcessModelApi(modelId.value);
    message.success('保存并部署成功');
  } catch (error: any) {
    message.error(error?.msg || '操作失败');
  }
}

// 返回
function handleBack() {
  router.back();
}

onMounted(async () => {
  modelId.value = route.params.id as string;
  if (!modelId.value) {
    message.error('模型ID不能为空');
    router.back();
    return;
  }

  await loadModelInfo();
  await loadBpmnXml();
});
</script>

<style scoped>
.workflow-designer-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.designer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 16px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.header-left {
  display: flex;
  align-items: center;
}

.model-name {
  font-size: 16px;
  font-weight: 500;
}

.designer-content {
  flex: 1;
  overflow: hidden;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>

